import {ref, Ref, shallowRef} from "vue";

export interface RadioButtonType {
  //按钮名称，此名称为key值
  name: string,
  //是否选中
  selected: boolean,
}

/**
 * 单选按钮组（两个参数的数量应一致，并且顺序对应）
 * @param initButtons 初始化按钮组
 * @param initPanels 初始化面板组件列表
 * @param cancelAble 按钮激活状态可以再次点击取消（如果不能取消，那么一旦激活，则至少有一个按钮是激活状态）
 */
export default function setupRadioButtonPanel<T extends RadioButtonType>(initButtons: T[] = [], initPanels: any[] = [],
                                                                         cancelAble = true) {
  //按钮组
  const buttons = ref(initButtons) as Ref<T[]>;
  //选中的按钮
  let selectedButton: Ref<T | null> = ref(null);
  //选中的组件
  let selectedPanel: Ref = shallowRef(null);

  //选中按钮
  function selectButton(item: T) {
    //处理选中按钮
    if (selectedButton.value) {
      if (selectedButton.value.name === item.name) {
        if (cancelAble) {
          //弹起按钮
          selectedButton.value.selected = false;
          selectedButton.value = null;
        } else
          return;
      } else {
        //替换选中按钮
        selectedButton.value.selected = false;
        item.selected = true;
        selectedButton.value = item;
      }
    } else {
      item.selected = true;
      selectedButton.value = item;
    }

    //根据选中的按钮，设置选中的面板
    if (selectedButton.value === null)
      selectedPanel.value = null;
    else {
      const index = buttons.value.findIndex(x => x.name === selectedButton.value!.name);
      if (index > -1) {
        selectedPanel.value = initPanels[index];
      } else
        selectedPanel.value = null;
    }
  }

  return {
    buttons, selectedButton, selectedPanel, selectButton
  }
}